package com.hangim.pce.common.search.aop;

import com.hangim.pce.common.search.annotation.ElasticSearch;
import com.hangim.pce.common.search.enums.ESActionType;
import com.hangim.pce.common.search.enums.ESEntityType;
import com.hangim.pce.common.search.service.ESSyncService;
import com.hangim.pce.model.*;
import com.google.common.collect.Maps;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

@Aspect
@Component
public class ElasticAspect {
    private static final Logger logger = LoggerFactory.getLogger(ElasticAspect.class);

    @Autowired
    private ESSyncService esSyncService;

    @AfterReturning(pointcut = "@annotation(com.hangim.pce.common.search.annotation.ElasticSearch)",
            returning = "returnVal")
    public void doAfter(JoinPoint joinPoint, Object returnVal) {
        try {
            // 获取注解信息
            Map<String, Enum> map = getAnnotationValue(joinPoint);
            ESEntityType entity = (ESEntityType) map.get("entity");
            ESActionType action = (ESActionType) map.get("action");

            if (ESEntityType.DISEASE.equals(entity)) {
                esSyncService.sendDisease((SysDisease) returnVal, action);
            } else if (ESEntityType.DRUG.equals(entity)) {
                esSyncService.sendDrug((BaseDrug) returnVal, action);
            } else if (ESEntityType.ELEMENT.equals(entity)) {
                esSyncService.sendElement((BaseElement) returnVal, action);
            } else if (ESEntityType.SYMPTOM.equals(entity)) {
                esSyncService.sendSymptom((SysSymptom) returnVal, action);
            }
        } catch (Exception e) {
            logger.error("get error in ActivityElasticAspect, the error message is: " + e);
            e.printStackTrace();
        }
    }

    /**
     * 获取注解对象
     */
    private ElasticSearch getAnnotation(JoinPoint joinPoint) throws Exception {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        return method.getAnnotation(ElasticSearch.class);
    }

    /**
     * 获取注解相应的值
     */
    protected Map<String, Enum> getAnnotationValue(JoinPoint joinPoint) throws Exception {
        ElasticSearch elasticSearch = getAnnotation(joinPoint);
        Map<String, Enum> map = Maps.newHashMap();
        map.put("entity", elasticSearch.entity());
        map.put("action", elasticSearch.action());
        return map;
    }
}
